import React, { Component } from 'react';
import { connect } from 'react-redux';
import { hashHistory } from 'react-router';
import { Alert, Breadcrumb, Button, Col, Form, Icon, Input, message, Modal, Radio, Row } from 'antd';
import * as actions from '../../actions/edit';
import { TYPE1, TYPE2, TYPE3, TYPE4, TYPE5 } from '../../constants';
import QRCode from 'qrcode.react';

let FormItem = Form.Item;
const RadioGroup = Radio.Group;
let { TextArea } = Input;
@Form.create({})
@connect(
  (state, props) => ({
    config: state.config,
    admin: state.admin,
  }), actions
)
export default class DynamicFieldSet extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    const { query } = this.props.location;
    this.props.getDetailById(query.id);
  }

  typeMap = {
    [TYPE1]: '文字',
    [TYPE2]: '图片',
    [TYPE3]: '音频',
    [TYPE4]: '视频',
    [TYPE5]: '标题',
  };

  remove = (k) => {
    this.props.form.validateFieldsAndScroll(err => {
      if (!err) {
        const { form } = this.props;
        const keys = form.getFieldValue('keys');
        form.setFieldsValue({
          keys: keys.filter(key => key.id !== k.id),
        });
        this.props.del(k);
      } else {
        message.error('请填写完整后再删除.');
      }
    });
  };

  add = (type, id, index) => () => {
    this.props.form.validateFieldsAndScroll({
      force: true,
    }, err => {
      if (!err) {
        const { form, admin, updateEdit } = this.props;
        // const keys = form.getFieldValue('keys');
        const keys = admin.edit.content.concat();
        const lastKey = keys[keys.length - 1];
        let finalKeys = [];
        if (id !== undefined) {
          finalKeys = keys.map((item, i) => {
            if (i > index) {
              item.id += 1;
            }
            return item;
          });
          finalKeys.splice(index + 1, 0, {
            id: id + 1,
            type,
            content: '',
          });
        } else {
          finalKeys = keys.concat({
            id: lastKey ? lastKey.id + 1 : 0,
            type,
            content: '',
          });
        }

        form.resetFields();

        form.setFieldsValue({
          keys: finalKeys,
        });

        updateEdit({
          content: finalKeys,
        });
      }
    });
  };

  qrCode() {
    const url = `https://babygogogo.cn/english/#/open/lesson/${this.props.admin.edit.openId}`;
    return (
      <div style={{ marginTop: '30px' }}>
        <div style={{ wordWrap: 'break-word', marginBottom: '15px', fontSize: '14px' }}>
          课程链接：
          <a href={url}>{url}</a>
        </div>
        <QRCode value={url} size={256} />
      </div>
    );
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err) => {
      if (!err) {
        this.props.submit(() => {
          Modal.info({
            title: '课程二维码',
            content: this.qrCode(),
            onOk: () => {
              hashHistory.push('/all');
            }
          });
        });
      }
    });
  };

  goBack() {
    hashHistory.goBack();
  }

  render() {
    const { changeName, changeType, changeAvatar, change, admin } = this.props;
    const { edit } = admin;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 },
      },
    };
    const formItemLayoutWithOutLabel = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 20, offset: 4 },
      },
    };

    let content = edit.content;
    // id = content.length > 0 ? content.length : 0;
    if (!Array.isArray(content)) {
      content = JSON.parse(content);
    }

    getFieldDecorator('keys', {
      initialValue: content,
    });
    const keys = getFieldValue('keys');
    const formItems = keys.map((k, index) => {
      return (
        <FormItem
          {...formItemLayout}
          label={this.typeMap[k.type]}
          required={false}
          key={`${k.id}-${index}`}
        >
          {getFieldDecorator(`names-${k.id}`, {
            initialValue: k.content,
            validateTrigger: ['onChange', 'onBlur'],
            rules: [
              {
                required: true,
                whitespace: true,
                message: "该项是必填项",
              }
            ],
          })(
            <TextArea
              name={k.id}
              placeholder={`请输入${this.typeMap[k.type]}`}
              style={{ width: '50%', marginRight: '15px' }}
              autosize={{ minRows: 1, maxRows: 8 }}
              onChange={e => change(e, k)}
            />
          )}
          {keys.length > 0 ? (
            <Icon
              key={`remove-${k.id}`}
              className="dynamic-delete-button"
              type="minus-circle-o"
              onClick={() => this.remove(k)}
            />
          ) : null}

          {keys.length > 0 &&
          <span style={{ margin: '0 0 0 10px' }}>
            <span>插入:</span>
            <Radio.Group value="small" style={{ margin: '0 0 0 10px' }}>
              <Radio.Button style={{ height: '20px', lineHeight: '20px', padding: '0 10px' }}
                            onClick={::this.add(TYPE1, k.id, index)}>文字</Radio.Button>
              <Radio.Button style={{ height: '20px', lineHeight: '20px', padding: '0 10px' }}
                            onClick={::this.add(TYPE2, k.id, index)}>图片</Radio.Button>
              <Radio.Button style={{ height: '20px', lineHeight: '20px', padding: '0 10px' }}
                            onClick={::this.add(TYPE3, k.id, index)}>音频</Radio.Button>
              <Radio.Button style={{ height: '20px', lineHeight: '20px', padding: '0 10px' }}
                            onClick={::this.add(TYPE4, k.id, index)}>视频</Radio.Button>
              <Radio.Button style={{ height: '20px', lineHeight: '20px', padding: '0 10px' }}
                            onClick={::this.add(TYPE5, k.id, index)}>标题</Radio.Button>
            </Radio.Group>
          </span>
          }

        </FormItem>
      );
    });

    return (
      <div className="container">
        <Breadcrumb style={{ marginBottom: '15px' }}>
          <Breadcrumb.Item>
            <Icon type="home" />
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <Icon type="folder-open" />
            <span>所有课程</span>
          </Breadcrumb.Item>
           <Breadcrumb.Item>
            <Icon type="edit" />
            <span>修改课程</span>
          </Breadcrumb.Item>
        </Breadcrumb>
         <Alert
           message={`正在修改课程【${edit.name}】`}
           description="如果不需要修改点击底部【返回】"
           type="warning"
         />
        <Row>
          <Col span="24">
            <Form onSubmit={this.handleSubmit} style={{ margin: '30px 0' }}>
              <FormItem
                {...formItemLayout}
                label="课程名称"
              >
                {getFieldDecorator('open-name', {
                  initialValue: edit.name,
                  rules: [
                    {
                      required: true, message: '请输入课程名称',
                    }
                  ],
                })(
                  <Input
                    style={{ width: '60%' }}
                    onChange={changeName}
                  />
                )}
              </FormItem>

              <FormItem
                {...formItemLayout}
                label="课程类型"
              >
                {getFieldDecorator('open-type', {
                  initialValue: edit.type,
                  rules: [
                    {
                      required: true, message: '请选择课程类型',
                    }
                  ],
                })(
                  <RadioGroup onChange={changeType}>
                    <Radio value={1}>试听课程（有效期六天）</Radio>
                    <Radio value={2}>报名课程（有效期一年）</Radio>
                  </RadioGroup>
                )}
              </FormItem>

              <FormItem
                {...formItemLayout}
                label="头像"
              >
                <div style={{ display: 'flex', alignItems: 'center' }}>
                {getFieldDecorator('open-avatar', {
                  initialValue: admin.edit.avatar,
                  rules: [
                    {
                      required: true, message: '请输入头像的地址',
                    }
                  ],
                })(
                  <TextArea
                    style={{ width: '60%' }}
                    autosize={{ minRows: 1, maxRows: 8 }}
                    onChange={changeAvatar}
                  />
                )}
                  <img style={{ margin: '0 0 0 20px', borderRadius: '50%' }} src={admin.edit.avatar} width="100"
                       height="100" />
                </div>
              </FormItem>

              {formItems}
              <FormItem {...formItemLayoutWithOutLabel}>
                <Button type="dashed" onClick={::this.add(TYPE1)} style={{ marginRight: '15px' }}>
                  <Icon type="plus" />
                  文字
                </Button>
                <Button type="dashed" onClick={::this.add(TYPE2)} style={{ marginRight: '15px' }}>
                  <Icon type="plus" />
                  图片
                </Button>
                <Button type="dashed" onClick={::this.add(TYPE3)} style={{ marginRight: '15px' }}>
                  <Icon type="plus" />
                  音频
                </Button>
                <Button type="dashed" onClick={::this.add(TYPE4)} style={{ marginRight: '15px' }}>
                  <Icon type="plus" />
                  视频
                </Button>
                <Button type="dashed" onClick={::this.add(TYPE5)} style={{ marginRight: '15px' }}>
                  <Icon type="plus" />
                  标题
                </Button>
              </FormItem>
              <FormItem {...formItemLayoutWithOutLabel}>
                <Button id="close" type="default" htmlType="button" onClick={this.goBack}
                        style={{ width: '20%', marginRight: '15px' }}>返回</Button>
                <Button id="submit" type="primary" htmlType="submit" style={{ width: '20%' }}>确认修改</Button>
              </FormItem>
            </Form>
          </Col>
        </Row>
      </div>
    );
  }
}
